package com.fjwt.gz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.db.dto.ActivityAwardDTO;
import com.fjwt.gz.db.dto.AwardVirtualDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.AwardVirtualVO;
import com.fjwt.gz.db.vo.ExportAwardVO;
import com.fjwt.gz.service.mapper.AwardVirtualMapper;
import com.fjwt.gz.util.Utils;
import com.fjwt.gz.util.quartz.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 虚拟奖品表 服务实现类
 * </p>
 *
 * @author shiyonghao
 * @since 2025-04-09
 */
@Slf4j
@Service
public class AwardVirtualService extends ServiceImpl<AwardVirtualMapper, AwardVirtualEntity> {

    @Autowired
    private AwardVirtualMapper awardVirtualMapper;
    @Autowired
    private AwardVirtualInsideService awardVirtualInsideService;
    @Autowired
    private AwardVirtualCdkService awardVirtualCdkService;
    @Autowired
    private AgentInfoService agentInfoService;

    @Autowired
    private AwardSettingService awardSettingService;

    @Autowired
    private ActivityAwardService activityAwardService;
    @Autowired
    private AwardMchService awardMchService;
    @Autowired
    private AwardAgentService awardAgentService;

    private static final Map<String, String> CODE_MAP = new HashMap<>();

    static {
        CODE_MAP.put("0", "价值");
        CODE_MAP.put("1", "金桂");
        CODE_MAP.put("2", "富嘉");
        CODE_MAP.put("3", "钻石");
        CODE_MAP.put("4", "鼎福");
    }

    /**
     * 获取列表
     */
    public List<AwardVirtualVO> queryList(AwardVirtualDTO awardVirtualDTO) {
        if (ObjectUtils.isEmpty(awardVirtualDTO) || ObjectUtils.isEmpty(awardVirtualDTO.getAgentNo())) {
            throw new BizException("请选择机构!");
        }
        if (StrUtil.isNotBlank(awardVirtualDTO.getAgentNo())) {
            awardVirtualDTO.setAgentNoList(agentInfoService.queryAllSubAgentNo(awardVirtualDTO.getAgentNo()));
            awardVirtualDTO.setAgentNo(null);
        }
        awardVirtualDTO.setState(Constants.AWARD_STATE.ONLINE);
        awardVirtualDTO.setIsConfigActivity(false);
        return baseMapper.queryList(awardVirtualDTO);
    }

    /**
     * 获取列表
     */
    public IPage<AwardVirtualVO> queryList(IPage iPage, AwardVirtualDTO awardVirtualDTO) {
        if (StrUtil.isNotBlank(awardVirtualDTO.getAgentNo())) {
            awardVirtualDTO.setAgentNoList(agentInfoService.queryAllSubAgentNo(awardVirtualDTO.getAgentNo()));
            awardVirtualDTO.setAgentNo(null);
        }
        IPage<AwardVirtualVO> awardVirtualVOIPage = baseMapper.queryList(iPage, awardVirtualDTO);
        List<AwardVirtualVO> records = awardVirtualVOIPage.getRecords();
        if (CollUtil.isNotEmpty(records)) {
            for (AwardVirtualVO awardVirtualVO : records) {
                AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardVirtualVO.getAgentNo());
                if (org.apache.commons.lang3.ObjectUtils.isNotEmpty(agentInfo)) {
                    awardVirtualVO.setAgentName(agentInfo.getAgentName());
                }
                if (awardVirtualVO.getType() != null) {
                    awardVirtualVO.setActivityName(awardVirtualVO.getType() == 1 ? "权益商城" : "福分商城");
                }

                String limitUserContent = awardVirtualVO.getLimitUserContent();
                if (StrUtil.isBlank(limitUserContent)) {
                    continue;
                }

                String[] split = limitUserContent.split(",");
                StringBuilder stringBuilder = new StringBuilder();
                for (String s : split) {
                    String replacement = CODE_MAP.get(s);
                    if (replacement != null) {
                        stringBuilder.append(replacement).append(";");
                    }
                }
                if (!stringBuilder.isEmpty()) {
                    String result = stringBuilder.substring(0, stringBuilder.lastIndexOf(";"));
                    awardVirtualVO.setLimitUserContent(result);
                }
            }
        }
        return awardVirtualVOIPage;
    }

    /**
     * 根据虚拟奖品id集合查询虚拟奖品集合
     *
     * @param virtualIdList 虚拟奖品id集合
     * @return 虚拟奖品列表
     */
    public List<AwardVirtualVO> getListByVirtualIdList(List<Long> virtualIdList) {
        return awardVirtualMapper.getListByVirtualIdList(virtualIdList);
    }

    /**
     * 新增保存虚拟奖品
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    public AwardVirtualVO saveAwardVirtual(AwardVirtualDTO dto) {
        if (dto.getVirtualInsideId() == null) {
            throw new BizException("请求参数不全，请检查！");
        }
        AwardVirtualEntity awardVirtualEntity = BeanUtil.copyProperties(dto, AwardVirtualEntity.class);
        //查询内部商品
        AwardVirtualInsideEntity goodsInsideEntity = awardVirtualInsideService.getById(awardVirtualEntity.getVirtualInsideId());
        if (goodsInsideEntity == null) {
            throw new BizException("选择的内部商品不存在");
        }
        List<AwardVirtualCdkEntity> cdkList = new ArrayList<>();
        if (goodsInsideEntity.getType() == Constants.VIRTUAL_AWARD.CDK) {
            //若为卡密商品 比较输入数量是否超过实际cdk数量
            cdkList = awardVirtualCdkService.list(AwardVirtualCdkEntity.gw()
                    .eq(AwardVirtualCdkEntity::getVirtualInsideId, goodsInsideEntity.getVirtualInsideId())
                    .eq(AwardVirtualCdkEntity::getIsConsume, 0)
                    .isNull(AwardVirtualCdkEntity::getVirtualId)
                    .orderByAsc(AwardVirtualCdkEntity::getCreatedAt));
            if (cdkList.size() < dto.getGoodsNum()) {
                throw new BizException("输入的数量大于cdk实际剩余数量");
            }
        }
        //后端生成批次号
        awardVirtualEntity.setBatchNo(Utils.generateBathNo());
        //默认商品领取数量为0
        awardVirtualEntity.setGoodsGet(0);
        //查询机构
        AgentInfoEntity agentInfo = agentInfoService.getById(awardVirtualEntity.getAgentNo());
        if (agentInfo == null) {
            throw new BizException("机构不存在");
        }
        awardVirtualEntity.setAgentNo(agentInfo.getAgentNo())
                .setAgentNo1(agentInfo.getAgentNo1())
                .setAgentNo2(agentInfo.getAgentNo2())
                .setAgentNo3(agentInfo.getAgentNo3())
                .setAgentNo4(agentInfo.getAgentNo4());

        save(awardVirtualEntity);
        //更新虚拟奖品cdk表前goodsNum数量的虚拟奖品id
        if (!CollectionUtils.isEmpty(cdkList)) {
            for (int i = 0; i < awardVirtualEntity.getGoodsNum(); i++) {
                cdkList.get(i).setVirtualId(awardVirtualEntity.getVirtualId());
            }
            awardVirtualCdkService.updateBatchById(cdkList);
        }

        AwardVirtualVO awardVirtualVO = new AwardVirtualVO();
        BeanUtils.copyProperties(awardVirtualEntity, awardVirtualVO);

        return awardVirtualVO;

    }

    /**
     * 获取详情
     *
     * @param virtualId
     * @return
     */
    public AwardVirtualVO getDetail(Long virtualId) {
        AwardVirtualEntity awardVirtualEntity = getById(virtualId);
        if (awardVirtualEntity == null) {
            throw new BizException("该记录不存在！");
        }
        AwardVirtualInsideEntity goodsInsideEntity = awardVirtualInsideService.getById(awardVirtualEntity.getVirtualInsideId());
        AwardVirtualVO awardVirtualVO = new AwardVirtualVO();
        BeanUtils.copyProperties(awardVirtualEntity, awardVirtualVO);
        awardVirtualVO.setAwardVirtualInsideEntity(goodsInsideEntity);
        awardVirtualVO.setAwardSetting(awardSettingService.getOne(AwardSettingEntity.gw()
                .eq(AwardSettingEntity::getAwardId, virtualId)
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.VIRTUAL_COUPON)));
        // 可核销卡券的商户
        List<AwardMchEntity> awardMchList = awardMchService.queryMchInfoByCouponId(virtualId, Constants.AWARD.VIRTUAL_COUPON);
        // 分配机构数量
        List<AwardAgentEntity> awardAgentEntityList = awardAgentService.getSavedData(virtualId, Constants.AWARD.VIRTUAL_COUPON);
        awardVirtualVO.setAwardMchList(awardMchList);
        awardVirtualVO.setAwardAgentList(awardAgentEntityList);

        if (ObjectUtils.isNotEmpty(awardVirtualEntity.getAgentNo())) {
            AgentInfoEntity agentInfo = agentInfoService.getAgentInfo(awardVirtualEntity.getAgentNo());
            if (ObjectUtils.isNotEmpty(agentInfo)) {
                awardVirtualVO.setAgentName(agentInfo.getAgentName());
            }
        }
        return awardVirtualVO;
    }

    /**
     * 修改虚拟券奖品详情
     *
     * @param dto
     */
    public void updateAwardVirtual(AwardVirtualDTO dto) {
        if (dto.getVirtualInsideId() == null || dto.getVirtualId() == null) {
            throw new BizException("请求参数不全，请检查！");
        }

        AwardVirtualEntity entity = getById(dto.getVirtualId());
        if (entity == null) {
            throw new BizException("该记录不存在！");
        }
        if (entity.getState() == Constants.AWARD_STATE.ONLINE) {
            throw new BizException("该状态不允许修改！");
        }

        dto.setCreatedAt(null);
        dto.setCreatedUid(null);
        dto.setBatchNo(null);
        dto.setUpdatedAt(new Date());
        AwardVirtualEntity awardVirtualEntity = BeanUtil.copyProperties(dto, AwardVirtualEntity.class);
        updateById(awardVirtualEntity);
    }

    /**
     * 修改虚拟奖品状态
     *
     * @param virtualId
     * @param state
     */
    public void updateState(Long virtualId, Integer state) {
        if (virtualId == null || state == null) {
            throw new BizException("请求参数不全，请检查！");
        }
        AwardVirtualEntity entity = getById(virtualId);
        if (entity == null) {
            throw new BizException("该记录不存在！");
        }
        entity.setState(state);
        updateById(entity);
    }

    /**
     * 删除虚拟奖品
     *
     * @param virtualId
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long virtualId) {
        if (virtualId == null) {
            throw new BizException("请求参数不全，请检查！");
        }
        AwardVirtualEntity awardEntity = getById(virtualId);
        if (awardEntity == null) {
            throw new BizException("该记录不存在！");
        }

        if (awardEntity.getState() == Constants.AWARD_STATE.ONLINE) {
            throw new BizException("配置完成的不允许删除！");
        }
        //是否绑定活动
        List<ActivityAwardEntity> list = activityAwardService.list(ActivityAwardEntity.gw()
                .eq(ActivityAwardEntity::getAwardId, virtualId)
                .eq(ActivityAwardEntity::getAwardType, Constants.AWARD.VIRTUAL_COUPON));
        if (CollUtil.isNotEmpty(list)) {
            throw new BizException("该奖品已配置活动，不能删除！");
        }
        //删除奖品配置信息
        awardSettingService.remove(AwardSettingEntity.gw()
                .eq(AwardSettingEntity::getAwardId, virtualId)
                .eq(AwardSettingEntity::getAwardType, Constants.AWARD.VIRTUAL_COUPON));
        //删除奖品
        removeById(virtualId);

    }

    public IPage<ExportAwardVO> activityVirtualDetail(IPage iPage , ActivityAwardDTO activityAwardDTO) {
        return baseMapper.activityVirtualDetail(iPage, activityAwardDTO);
    }
    public List<ExportAwardVO> activityVirtualDetail(ActivityAwardDTO activityAwardDTO) {
        return baseMapper.activityVirtualDetail(activityAwardDTO);
    }

}
